package com.lee.serviceagent.ocr.tesseractbaidu;

import com.baidu.aip.ocr.AipOcr;
import com.lee.serviceagent.ocr.tesseractsec.IdCardInfo;
import lombok.extern.slf4j.Slf4j;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.HashMap;

/**
 * @author lee
 * @description class
 * @date 2025/8/19 下午4:37
 */
@Service
@Slf4j
public class BaiduOcrService {
    @Value("${baidu.ocr.appId}")
    private String appId;

    @Value("${baidu.ocr.apiKey}")
    private String apiKey;

    @Value("${baidu.ocr.secretKey}")
    private String secretKey;

    private AipOcr client;

    @PostConstruct
    public void init() {
        client = new AipOcr(appId, apiKey, secretKey);
    }

    public IdCardInfo recognizeIdCard(byte[] imageData, boolean isFront) throws JSONException {
        HashMap<String, String> options = new HashMap<>();
        options.put("detect_direction", "true");
        options.put("detect_risk", "false");

        String idCardSide = isFront ? "front" : "back";
        JSONObject res = client.idcard(imageData, idCardSide, options);
        log.info("res:{}", res);

        // 解析百度OCR返回的JSON数据
        return parseBaiduOcrResult(res, isFront);
    }

    private IdCardInfo parseBaiduOcrResult(JSONObject res, boolean isFront) throws JSONException {
        IdCardInfo info = new IdCardInfo();
        JSONObject wordsResult = res.getJSONObject("words_result");

        if (isFront) {
            // 解析正面信息
            info.setName(wordsResult.getJSONObject("姓名").getString("words"));
            info.setGender(wordsResult.getJSONObject("性别").getString("words"));
            info.setNation(wordsResult.getJSONObject("民族").getString("words"));
            info.setBirthDate(wordsResult.getJSONObject("出生").getString("words"));
            info.setAddress(wordsResult.getJSONObject("住址").getString("words"));
            info.setIdNumber(wordsResult.getJSONObject("公民身份号码").getString("words"));
        } else {
            // 解析背面信息
            info.setIssuingAuthority(wordsResult.getJSONObject("签发机关").getString("words"));
            info.setValidPeriod(wordsResult.getJSONObject("有效期限").getString("words"));
        }

        return info;
    }

}
